package com.fivefu.core.hillstone.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fivefu.base.common.utils.date.DateUtils;
import com.fivefu.core.hillstone.dto.request.BusChannelDto;
import com.fivefu.core.hillstone.dto.request.BusEnterVideo;
import com.fivefu.core.hillstone.dto.request.BusGpsDto;
import com.fivefu.core.hillstone.dto.request.BusMonitorDto;
import com.fivefu.core.hillstone.dto.response.BusEquipmentDto;
import com.fivefu.core.hillstone.dto.response.BusMonitorData;
import com.fivefu.core.hillstone.dto.response.TBusEquipmentData;
import com.fivefu.core.hillstone.dto.response.TColsnote;
import com.fivefu.core.hillstone.entity.*;
import com.fivefu.core.hillstone.mapper.DbHillstoneBusEquipmentGpsMapper;
import com.fivefu.core.hillstone.services.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 大华公交车设备历史点位信息 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-11-24 10:18:56
 */
@Service
public class DbHillstoneBusEquipmentGpsServiceImpl extends ServiceImpl<DbHillstoneBusEquipmentGpsMapper, DbHillstoneBusEquipmentGps> implements DbHillstoneBusEquipmentGpsService {

    private Logger logger = LoggerFactory.getLogger(DbHillstoneBusEquipmentGpsServiceImpl.class);

    @Autowired
    private HillstoneService hillstoneService;

    @Autowired
    private DbHillstoneDeviceService dbHillstoneDeviceService;

    @Autowired
    private DbHillstoneChannelService dbHillstoneChannelService;

    @Autowired
    private DbHillstoneOrganizationDeviceService dbHillstoneOrganizationDeviceService;

    @Autowired
    private DbHillstoneBusequipmentGpsHistoryService dbHillstoneBusequipmentGpsHistoryService;

    @Override
    public String getBusData() {
        //设置参数提交方式
        BusMonitorDto busMonitorDto = new BusMonitorDto();
        List<Integer> arrayList = new ArrayList<>();
        busMonitorDto.setDeviceCodes(arrayList);
        busMonitorDto.setDeviceCodes(arrayList);
        //将请求对象转换为json字符串
        String bodys = JSON.toJSONString(busMonitorDto);
        /*获取公交车设备基础信息列表*/
        String data = hillstoneService.postHillstoneJson("/admin/API/tree/devices", bodys);
        if (data != null) {
            BusEquipmentDto busEquipmentDto = JSON.parseObject(data, BusEquipmentDto.class);
            String resultData = busEquipmentDto.getData();
            BusMonitorData busMonitorDataJson = JSON.parseObject(resultData, BusMonitorData.class);
            String devices = busMonitorDataJson.getDevices();
            if (devices != null) {
                List<BusEquipmentDto> busEquipmentDtos = JSON.parseArray(devices, BusEquipmentDto.class);
                for (BusEquipmentDto equipmentDto : busEquipmentDtos) {
                    /*添加设备信息表*/
                    DbHillstoneDevice dbHillstoneDevice = new DbHillstoneDevice();
                    dbHillstoneDevice.setDeviceCode(equipmentDto.getCode());
                    dbHillstoneDevice.setDeviceName(equipmentDto.getName());
                    dbHillstoneDevice.setOnline(Integer.parseInt(equipmentDto.getStatus()));
                    dbHillstoneDevice.setOrganizationCode(equipmentDto.getOrgCode());
                    dbHillstoneDevice.setDeviceId(equipmentDto.getCode());
                    dbHillstoneDevice.setDeviceManufacturer("MP01");
                    dbHillstoneDevice.setDeviceIp(equipmentDto.getDeviceIp());
                    if (equipmentDto.getDevicePort() != null) {
                        dbHillstoneDevice.setDevicePort(Integer.parseInt(equipmentDto.getDevicePort()));
                    }
                    dbHillstoneDevice.setLoginName(equipmentDto.getUserName());
                    dbHillstoneDevice.setProtocolType("VH17");
                    dbHillstoneDevice.setSubType(equipmentDto.getType());
                    dbHillstoneDevice.setDeviceType(equipmentDto.getCategory());
                    if (equipmentDto.getDeviceModelStr() != null) {
                        dbHillstoneDevice.setDeviceModel(equipmentDto.getDeviceModelStr());
                    }
                    dbHillstoneDevice.setDeviceSn(equipmentDto.getSn());
                    dbHillstoneDevice.setRegistDeviceCode(equipmentDto.getCode());
                    dbHillstoneDevice.setOfflineReason(equipmentDto.getOfflineReason());
                    dbHillstoneDevice.setProxyIp(equipmentDto.getProxyIp());
                    dbHillstoneDevice.setProxyPort(equipmentDto.getProxyPort());
                    dbHillstoneDevice.setPassword(equipmentDto.getPassword());
                    dbHillstoneDevice.setLoginType(equipmentDto.getLoginType());
                    DbHillstoneDevice deviceServiceOne = dbHillstoneDeviceService.getOne(new QueryWrapper<DbHillstoneDevice>().eq("is_delete", 0).eq("device_code", equipmentDto.getCode()));
                    if (deviceServiceOne != null) {
                        dbHillstoneDevice.setId(deviceServiceOne.getId());
                        dbHillstoneDevice.setUpdatedTime(LocalDateTime.now());
                        dbHillstoneDeviceService.updateById(dbHillstoneDevice);
                    } else {
                        dbHillstoneDeviceService.save(dbHillstoneDevice);
                    }
                    /*获取设备通道信息*/
                    List<BusEquipmentDto> busEquipmentDtoList = JSON.parseArray(equipmentDto.getUnits(), BusEquipmentDto.class);
                    for (BusEquipmentDto dto : busEquipmentDtoList) {
                        List<BusEquipmentDto> busEquipmentDtoData = JSON.parseArray(dto.getChannels(), BusEquipmentDto.class);
                        for (BusEquipmentDto busEquipmentDtoDatum : busEquipmentDtoData) {
                            DbHillstoneChannel dbHillstoneChannel = new DbHillstoneChannel();
                            dbHillstoneChannel.setChannelCode(busEquipmentDtoDatum.getChannelCode());
                            dbHillstoneChannel.setName(busEquipmentDtoDatum.getChannelName());
                            dbHillstoneChannel.setOrganizationCode(equipmentDto.getOrgCode());
                            dbHillstoneChannel.setDeviceCode(equipmentDto.getCode());
                            if (equipmentDto.getChannelSeq() != null) {
                                dbHillstoneChannel.setChannelSeq(Integer.parseInt(equipmentDto.getChannelSeq()));
                            }
                            if (equipmentDto.getStatus() != null) {
                                dbHillstoneChannel.setOnline(Integer.parseInt(equipmentDto.getStatus()));
                            }
                            dbHillstoneChannel.setUnitType(dto.getUnitType());
                            DbHillstoneChannel dbHillstoneChannelServiceOne = dbHillstoneChannelService.getOne(new QueryWrapper<DbHillstoneChannel>().eq("is_delete", 0).eq("channel_code", busEquipmentDtoDatum.getChannelCode()));
                            if (dbHillstoneChannelServiceOne != null ) {
                                dbHillstoneChannel.setId(dbHillstoneChannelServiceOne.getId());
                                dbHillstoneChannel.setUpdatedTime(LocalDateTime.now());
                                dbHillstoneChannelService.updateById(dbHillstoneChannel);
                            } else {
                                dbHillstoneChannelService.save(dbHillstoneChannel);
                                /*添加设备组织通道关联表*/
                                DbHillstoneOrganizationDevice dbHillstoneOrganizationDevice = new DbHillstoneOrganizationDevice();
                                dbHillstoneOrganizationDevice.setOrgCode(equipmentDto.getOrgCode());
                                dbHillstoneOrganizationDevice.setChannelCode(busEquipmentDtoDatum.getChannelCode());
                                dbHillstoneOrganizationDevice.setDeviceCode(equipmentDto.getCode());
                                dbHillstoneOrganizationDeviceService.save(dbHillstoneOrganizationDevice);
                            }
                        }
                    }

                }
            }
        }
        return "添加设备基础信息成功";
    }

    /**
     * 获取公交车轨迹列表
     */
    @Override
    public String getBusGpsData() {
        List<List<BusGpsDto>> busData = new ArrayList<>();
        List<String> deviceCodeData = new ArrayList<>();
        List<DbHillstoneDevice> dbHillstoneDevices = dbHillstoneDeviceService.list(new QueryWrapper<DbHillstoneDevice>().eq("is_delete", 0).eq("protocol_type", "VH17"));
        /*数据量过大请求超时取一半数据*/
        for (int i = 0; i < dbHillstoneDevices.size()/2; i++) {
            deviceCodeData.add(dbHillstoneDevices.get(i).getDeviceCode());
        }
        Map<String, Object> map = new HashMap() {{put("deviceCodeList", deviceCodeData);}};
        String deviceCodeList = JSONObject.toJSONString(map);
        String getGpsData = hillstoneService.postHillstoneJson("/vehicleServer/gps/getLastLocation", deviceCodeList);
        BusGpsDto busGpsDto = JSON.parseObject(getGpsData, BusGpsDto.class);
        List<BusGpsDto> busGpsDtos = JSON.parseArray(busGpsDto.getResult(), BusGpsDto.class);
        busData.add(busGpsDtos);
        /*数据量过大请求超时取另一半数据*/
        List<String> deviceCodeData2 = new ArrayList<>();
        for (int i = dbHillstoneDevices.size()/2 + 1; i < dbHillstoneDevices.size(); i++) {
            deviceCodeData2.add(dbHillstoneDevices.get(i).getDeviceCode());
        }
        Map<String, Object> map2 = new HashMap() {{put("deviceCodeList", deviceCodeData2);}};
        String deviceCodeList2 = JSONObject.toJSONString(map2);
        String getGpsData2 = hillstoneService.postHillstoneJson("/vehicleServer/gps/getLastLocation", deviceCodeList2);
        BusGpsDto busGpsDto2 = JSON.parseObject(getGpsData2, BusGpsDto.class);
        List<BusGpsDto> busGpsDtos2 = JSON.parseArray(busGpsDto2.getResult(), BusGpsDto.class);
        busData.add(busGpsDtos2);
        /*公交车设备信息列表*/
        List<DbHillstoneBusequipmentGpsHistory> dbHillstoneBusEquipmentGpsList = new ArrayList<>();
        /*公交车设备添加最新点位信息*/
        List<DbHillstoneBusEquipmentGps> busEquipmentRealTimeGpsAddList = new ArrayList<>();
        /*公交车设备更新最新点位信息*/
        List<DbHillstoneBusEquipmentGps> busEquipmentRealTimeGpsModifyList = new ArrayList<>();
        for (List<BusGpsDto> busDatum : busData) {
            for (BusGpsDto gpsDto : busDatum) {
                String deviceCode = gpsDto.getDeviceCode();
                String gpsX = gpsDto.getGpsX();
                String gpsY = gpsDto.getGpsY();
                String speed = gpsDto.getSpeed();
                String angle = gpsDto.getAngle();
                String direction = gpsDto.getDirection();
                /*时间戳转换*/
                String capTime = gpsDto.getCapTime();
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long date_temp = Long.valueOf(capTime);
                String date_string = sdf.format(new Date(date_temp * 1000L));
                LocalDateTime capDateTime = DateUtils.parse(date_string);
                String isOnline = gpsDto.getIsOnline();
                /*添加设备历史轨迹表*/
                DbHillstoneBusequipmentGpsHistory dbHillstoneBusequipmentGpsHistory = new DbHillstoneBusequipmentGpsHistory();
                dbHillstoneBusequipmentGpsHistory.setCreatedTime(LocalDateTime.now());
                dbHillstoneBusequipmentGpsHistory.setAngle(BigDecimal.valueOf(Double.parseDouble(angle)));
                dbHillstoneBusequipmentGpsHistory.setDeviceCode(deviceCode);
                dbHillstoneBusequipmentGpsHistory.setGpsX(BigDecimal.valueOf(Double.parseDouble(gpsX)));
                dbHillstoneBusequipmentGpsHistory.setGpsY(BigDecimal.valueOf(Double.parseDouble(gpsY)));
                dbHillstoneBusequipmentGpsHistory.setSpeed(BigDecimal.valueOf(Double.parseDouble(speed)));
                dbHillstoneBusequipmentGpsHistory.setDirection(direction);
                dbHillstoneBusequipmentGpsHistory.setIsOnline(Integer.parseInt(isOnline));
                if (capTime != null) {
                    dbHillstoneBusequipmentGpsHistory.setCapTime(capDateTime);
                }
                dbHillstoneBusEquipmentGpsList.add(dbHillstoneBusequipmentGpsHistory);
                /*添加实时轨迹表*/
                DbHillstoneBusEquipmentGps dbHillstoneBusEquipmentRealTimeGps = new DbHillstoneBusEquipmentGps();
                dbHillstoneBusEquipmentRealTimeGps.setDeviceCode(deviceCode);
                dbHillstoneBusEquipmentRealTimeGps.setGpsX(BigDecimal.valueOf(Double.parseDouble(gpsX)));
                dbHillstoneBusEquipmentRealTimeGps.setGpsY(BigDecimal.valueOf(Double.parseDouble(gpsY)));
                dbHillstoneBusEquipmentRealTimeGps.setIsOnline(Integer.parseInt(isOnline));
                dbHillstoneBusEquipmentRealTimeGps.setAngle(BigDecimal.valueOf(Double.parseDouble(angle)));
                dbHillstoneBusEquipmentRealTimeGps.setSpeed(BigDecimal.valueOf(Double.parseDouble(speed)));
                dbHillstoneBusEquipmentRealTimeGps.setDirection(direction);
                if (capTime != null) {
                    dbHillstoneBusEquipmentRealTimeGps.setCapTime(capDateTime);
                }
                DbHillstoneBusEquipmentGps one = getOne(new QueryWrapper<DbHillstoneBusEquipmentGps>().eq("is_delete", 0).eq("device_code", deviceCode));
                if (one != null) {
                    dbHillstoneBusEquipmentRealTimeGps.setId(one.getId());
                    dbHillstoneBusEquipmentRealTimeGps.setUpdatedTime(LocalDateTime.now());
                    busEquipmentRealTimeGpsModifyList.add(dbHillstoneBusEquipmentRealTimeGps);
                } else {
                    busEquipmentRealTimeGpsAddList.add(dbHillstoneBusEquipmentRealTimeGps);
                }
            }
        }
        /*添加设备历史点位信息*/
        dbHillstoneBusequipmentGpsHistoryService.saveBatch(dbHillstoneBusEquipmentGpsList);
        /*添加设备最新点位信息*/
        saveBatch(busEquipmentRealTimeGpsAddList);
        /*更新设备最新点位信息*/
        updateBatchById(busEquipmentRealTimeGpsModifyList);
        return "公交车历史轨迹添加完成！";
    }

    /**
     * 公交车监控视频播放
     * params deviceCode (设备编码)
     */
    @Override
    public List<Map> surveillanceVideo(String deviceCode) {
        List<Integer> list = new ArrayList<>();
        List<Integer> categoriesList = new ArrayList<>();
        list.add(Integer.parseInt(deviceCode));
        BusMonitorDto busMonitorDto = new BusMonitorDto();
        busMonitorDto.setDeviceCodes(list);
        busMonitorDto.setCategories(categoriesList);
        String data = JSONObject.toJSONString(busMonitorDto);
        /*根据设备编号获取设备树*/
        String result = hillstoneService.postHillstoneJson("/admin/API/tree/devices", data);
        logger.info(result + "设备树");
        /*结果集*/
        List<Map> mapList = new ArrayList<>();
        if (result != null) {
            /*获取设备树中的通道编码*/
            BusMonitorData busMonitorData = JSON.parseObject(result, BusMonitorData.class);
            String data2 = busMonitorData.getData();
            BusMonitorData busMonitorDataJson = JSON.parseObject(data2, BusMonitorData.class);
            String devices = busMonitorDataJson.getDevices();
            if (devices != null) {
                List<BusMonitorData> busMonitorData3 = JSON.parseArray(devices, BusMonitorData.class);
                for (BusMonitorData monitorData : busMonitorData3) {
                    List<BusMonitorData> busMonitorDataJson2 = JSON.parseArray(monitorData.getUnits(), BusMonitorData.class);
                    for (BusMonitorData busmonitorData : busMonitorDataJson2) {
                        List<BusMonitorData> busMonitorDataJson3 = JSON.parseArray(busmonitorData.getChannels(), BusMonitorData.class);
                        for (BusMonitorData busdata : busMonitorDataJson3) {
                            Map<String, String> map = new HashMap<>();
                            /*获取设备在线状态 1：在线 0：离线*/
                            String channelCode = busdata.getChannelCode();
                            BusChannelDto busChannelDto = new BusChannelDto();
                            busChannelDto.setChannelId(channelCode);
                            busChannelDto.setDataType("1");
                            busChannelDto.setStreamType("1");
                            BusEnterVideo datas = new BusEnterVideo();
                            datas.setData(busChannelDto);
                            String bodyData = JSONObject.toJSONString(datas);
                            /*获取通道中实时播放地址 url1 url2(可直接播放)*/
                            String rtspData = hillstoneService.postHillstoneJson("/admin/API/MTS/Video/StartVideo", bodyData);
                            logger.info("播放地址" + rtspData);
                            if (rtspData != null) {
                                BusMonitorData busMonitorData1 = JSON.parseObject(rtspData, BusMonitorData.class);
                                String data1 = busMonitorData1.getData();
                                BusMonitorData busMonitorData2 = JSON.parseObject(data1, BusMonitorData.class);
                                if (busMonitorData2.getUrl() != null) {
                                    String[] url2split = busMonitorData2.getUrl().split("rtsp");
                                    String s = url2split[1];
                                    s = s.substring(0,s.length()-1);
                                    if(s.contains("172.16.50.19")) {
                                        String code = s.substring(56, 59);
                                        s = s.substring(48, 55);
                                        map.put("url2", "rtsp://172.16.50.19:9090/dss/monitor/params?cameraid="+ s +"%"+ code +"&substream=1" );
                                    } else {
                                        map.put("url2","rtsp" + s);
                                    }
                                }
                            }
                            mapList.add(map);
                        }
                    }
                }
            }
        }
        return mapList;
    }

    @Override
    public Map<String, List> inquireBusData(String deviceName, String isOnline) {
        Map<String, List> map = new HashMap<>();
        List<TColsnote> colsnotesList = new ArrayList<>();
        TColsnote tColsnote = new TColsnote();
        tColsnote.setColnote("设备编码");
        tColsnote.setColname("deviceCode");
        colsnotesList.add(tColsnote);
        TColsnote tColsnote1 = new TColsnote();
        tColsnote1.setColnote("设备名称");
        tColsnote1.setColname("deviceName");
        colsnotesList.add(tColsnote1);
        TColsnote tColsnote2 = new TColsnote();
        tColsnote2.setColnote("经度");
        tColsnote2.setColname("gpsx");
        colsnotesList.add(tColsnote2);
        TColsnote tColsnote3 = new TColsnote();
        tColsnote3.setColnote("纬度");
        tColsnote3.setColname("gpsy");
        colsnotesList.add(tColsnote3);
        TColsnote tColsnote4 = new TColsnote();
        tColsnote4.setColnote("设备是否在线");
        tColsnote4.setColname("isOnline");
        colsnotesList.add(tColsnote4);
        TColsnote tColsnote5 = new TColsnote();
        tColsnote5.setColnote("Gps采集时间");
        tColsnote5.setColname("capTime");
        colsnotesList.add(tColsnote5);
        TColsnote tColsnote6 = new TColsnote();
        tColsnote6.setColnote("速度");
        tColsnote6.setColname("speed");
        colsnotesList.add(tColsnote6);
        TColsnote tColsnote7 = new TColsnote();
        tColsnote7.setColnote("角度");
        tColsnote7.setColname("angle");
        colsnotesList.add(tColsnote7);
        TColsnote tColsnote8 = new TColsnote();
        tColsnote8.setColnote("方向");
        tColsnote8.setColname("direction");
        colsnotesList.add(tColsnote8);
        map.put("colsnote", colsnotesList);
        List<TBusEquipmentData> busData = baseMapper.inquireBusData(deviceName, isOnline);
        map.put("data", busData);
        return map;
    }
}
